package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"os"
)

const privatefile1Name = `./privateRsaKey.pem`
const publicfile1Name = `./publicRsaKey.pem`

// bits 生成多少位的私钥
func genratKeyPair(bits int) error {
	// 1.生成私钥
	//rand.Reader 随机数生成器
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}
	//
	// 2.对生成私钥进行编码处理 x509
	priDerText := x509.MarshalPKCS1PrivateKey(privateKey)
	fmt.Println("--priDerText--=",priDerText)
	fmt.Println("--strpriDerText--=",base64.StdEncoding.EncodeToString(priDerText))
	//3. 创建block代表pem结构
	block := pem.Block{
		Type:    "VOCALOID RSA KEY",
		Headers: nil,
		Bytes:   priDerText, //私钥进行编码处理的数据
	}
	//4. 长江block代表结构，写入文件
	file1, err := os.Create(privatefile1Name)
	if err != nil {
		return err
	}
	err = pem.Encode(file1, &block)
	if err != nil {
		return err
	}

	fmt.Println("++++++++++++++++++++++开始生成公钥+++++++++++++++++++++++++")
	/**
	获取公钥
	*/
	publicKey := privateKey.PublicKey
	pubDerText := x509.MarshalPKCS1PublicKey(&publicKey)
	block = pem.Block{
		Type:    "VOCALOID RSA Public KEY",
		Headers: nil,
		Bytes:   pubDerText,
	}
	file2, err := os.Create(publicfile1Name)
	if err != nil {
		return err
	}
	err = pem.Encode(file2, &block)
	if err != nil {
		return err
	}
	return nil
}

func main() {
	fmt.Println("生成私钥中")
	err := genratKeyPair(1024)
	if err != nil {
		fmt.Println("生成失败：", err)
	}
	fmt.Println("生成成功！")
}
